import 'dart:convert';
import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/services/share_service.dart';
import 'package:blurb/common/values/images.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserService {
  static const String _userListKey = 'user_list';
  static const String _currentUserKey = 'current_user';

  // 初始化默认用户
  static Future<void> initDefaultUsers() async {
    final prefs = await SharedPreferences.getInstance();
    final userListStr = prefs.getString(_userListKey);

    // 如果用户列表为空，创建默认用户
    if (userListStr == null) {
      final List<User> defaultUsers = [
        User(
          id: 1,
          username: 'test1',
          password: '654321',
          nickname: 'SunShine',
          avatar: MIP.avatar1,
          sign: 'Stay protected, stay stylish. #SunscreenDaily',
        ),
        User(
          id: 2,
          username: 'test2',
          password: '654321',
          nickname: 'UVBlocker',
          avatar: MIP.avatar2,
          sign: 'Sun damage is cumulative. Protect your future self!',
        ),
        User(
          id: 3,
          username: 'test3',
          password: '654321',
          nickname: 'GlowGuard',
          avatar: MIP.avatar3,
          sign: 'SPF enthusiast. Sharing my anti-aging secrets!',
        ),
        User(
          id: 4,
          username: 'test4',
          password: '654321',
          nickname: 'SkinSavvy',
          avatar: MIP.avatar4,
          sign: 'Life motto: Reapply every two hours!',
        ),
      ];

      // 将用户列表转换为JSON并保存
      final List<Map<String, dynamic>> userMapList = defaultUsers.map((user) => user.toJson()).toList();
      await prefs.setString(_userListKey, jsonEncode(userMapList));
      
      // 初始化默认分享
      await ShareService.initDefaultShares();
    }
  }

  // 获取所有用户
  static Future<List<User>> getAllUsers() async {
    final prefs = await SharedPreferences.getInstance();
    final userListStr = prefs.getString(_userListKey);

    if (userListStr != null) {
      final List<dynamic> userMapList = jsonDecode(userListStr);
      return userMapList.map((userMap) => User.fromJson(userMap)).toList();
    }

    return [];
  }

  // 根据用户名和密码验证登录
  static Future<User?> login(String username, String password) async {
    final users = await getAllUsers();
    
    for (final user in users) {
      if (user.username == username && user.password == password) {
        // 保存当前登录用户
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(_currentUserKey, jsonEncode(user.toJson()));
        return user;
      }
    }
    
    return null;
  }

  // 注册新用户
  static Future<bool> register(User newUser) async {
    final users = await getAllUsers();
    
    // 检查用户名是否已存在
    final usernameExists = users.any((user) => user.username == newUser.username);
    if (usernameExists) {
      return false;
    }

    // 添加新用户
    users.add(newUser);
    
    // 保存用户列表
    final prefs = await SharedPreferences.getInstance();
    final List<Map<String, dynamic>> userMapList = users.map((user) => user.toJson()).toList();
    await prefs.setString(_userListKey, jsonEncode(userMapList));
    
    return true;
  }

  // 获取当前登录用户
  static Future<User?> getCurrentUser() async {
    final prefs = await SharedPreferences.getInstance();
    final currentUserStr = prefs.getString(_currentUserKey);
    
    if (currentUserStr != null) {
      return User.fromJson(jsonDecode(currentUserStr));
    }
    
    return null;
  }

  // 退出登录
  static Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_currentUserKey);
  }
  
  // 更新用户信息
  static Future<bool> updateUserInfo(User updatedUser) async {
    final users = await getAllUsers();
    final prefs = await SharedPreferences.getInstance();
    
    // 查找并更新用户
    final index = users.indexWhere((user) => user.id == updatedUser.id);
    if (index != -1) {
      users[index] = updatedUser;
      
      // 保存用户列表
      final List<Map<String, dynamic>> userMapList = users.map((user) => user.toJson()).toList();
      await prefs.setString(_userListKey, jsonEncode(userMapList));
      
      // 如果更新的是当前用户，也更新当前用户信息
      final currentUser = await getCurrentUser();
      if (currentUser != null && currentUser.id == updatedUser.id) {
        await prefs.setString(_currentUserKey, jsonEncode(updatedUser.toJson()));
      }
      
      return true;
    }
    
    return false;
  }

  // 删除账户
  static Future<bool> deleteAccount(int userId) async {
    final users = await getAllUsers();
    final prefs = await SharedPreferences.getInstance();
    
    // 查找并删除用户
    final index = users.indexWhere((user) => user.id == userId);
    if (index != -1) {
      // 删除用户
      users.removeAt(index);
      
      // 保存用户列表
      final List<Map<String, dynamic>> userMapList = users.map((user) => user.toJson()).toList();
      await prefs.setString(_userListKey, jsonEncode(userMapList));
      
      // 如果删除的是当前登录的用户，清除当前用户信息
      final currentUser = await getCurrentUser();
      if (currentUser != null && currentUser.id == userId) {
        await prefs.remove(_currentUserKey);
      }
      
      return true;
    }
    
    return false;
  }
  
  // 通过用户ID获取用户信息
  static Future<User?> getUserById(int userId) async {
    final users = await getAllUsers();
    final index = users.indexWhere((user) => user.id == userId);
    if (index != -1) {
      return users[index];
    }
    return null;
  }
} 